package com.wpen.unit.core;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.DisposableBean;

import com.wpen.unit.AppVariables;

import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务线程
 * 
 * @author Wang Peng
 * @date 2022-12-06
 */
@Slf4j
public class AgentScheduleWorker implements DisposableBean {
    private static final AgentScheduleWorker instance = new AgentScheduleWorker();

    private AgentScheduleWorker() {
    }

    public static AgentScheduleWorker getInstance() {
        return instance;
    }

    private final long loopRead = 15000;

    private Thread healthReportThread;
    private volatile boolean healthThreadRunning = true;


    public void start() {
        log.info(this.getClass().getName() + " start...");

        healthReportThread = new Thread(new Runnable() {
            // 常驻在线子线程
            @Override
            public void run() {
                while (!AppVariables.kernelStarted) {
                    // 容器没有完成启动，等待
                    try {
                        TimeUnit.MILLISECONDS.sleep(1000);
                    } catch (InterruptedException e) {
                        log.error(e.getMessage(), e);
                    }
                }
                // 批次扫描线程
                while (healthThreadRunning) {
                    // 每次执行耗时，毫秒
                    long start = System.currentTimeMillis();
                    try {
                    } catch (Exception e) {
                        log.error("batchObserverThread Exception>" + e.getMessage(), e);
                    } finally {
                        try {
                            long cost = System.currentTimeMillis() - start;
                            TimeUnit.MILLISECONDS.sleep(loopRead - cost);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        healthReportThread.setDaemon(true);
        healthReportThread.setName("agent-health-report");
        healthReportThread.start();
        log.info(healthReportThread.getName() + " running...");

    }

    public void destroy() {
        healthThreadRunning = false;
        log.info(this.getClass().getName() + " bye..");
    }

}
